//
//  MNDPlusRecordDetailViewController.m
//  PlusTenderDemo
//
//  Created by Vitas on 2018/7/17.
//  Copyright © 2018年 Bylongma. All rights reserved.
//

#import "MNDPlusRecordDetailViewController.h"
#import "MNDTenderProjectViewController.h"
#import "MNDEarnRecordViewController.h"
#import "MNDPlusDetailCell.h"
#import "MNDPlusRecordDetailModel.h"
#import "MNDWebViewController.h"

#define kMNDPlusDetailCell @"MNDPlusDetailCell"

@interface MNDPlusRecordDetailViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
//授权金额
@property (weak, nonatomic) IBOutlet UILabel *borrowMoneyLabel;

@property (weak, nonatomic) IBOutlet UILabel *alrealyMoneyLabel;
//预期收益
@property (weak, nonatomic) IBOutlet UILabel *interestLabel;

//锁定期限
@property (weak, nonatomic) IBOutlet UILabel *deadlineLabel;
//授权时间
@property (weak, nonatomic) IBOutlet UILabel *startTimeLabel;
//回款时间
@property (weak, nonatomic) IBOutlet UILabel *returnTimeLabel;
//年化率
@property (weak, nonatomic) IBOutlet UILabel *yearAprLabel;

//平台奖励
@property (weak, nonatomic) IBOutlet UILabel *awardTipLabel;
@property (weak, nonatomic) IBOutlet UILabel *awardLabel;

@property(nonatomic, strong) MNDPlusRecordDetailModel *detailModel;
@property (weak, nonatomic) IBOutlet UIButton *exitButton;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;

@end

@implementation MNDPlusRecordDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (@available(iOS 11, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    [self loadData];
    
    if (self.shouldCustomBack) {
        [self customBackBarButton];
    }
    // Do any additional setup after loading the view.
}

- (void)customBackBarButton {
    UIImage *backImage = [UIImage imageNamed:@"navi_back_btn_black"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(backAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItem = backBarButtonItem;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem];
    }
    
}

- (void)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)loadData {
    
    kdeclare_weakself;
    [NetworkProgressHUD showHud];
    NSDictionary *params = @{
                             @"sign_id":self.sign_id
                             };
    [APIManager sendRequestWithURL:API_AUTO_PLUS_BORROW_DETAIL parameters:[MNDSign signedParamWithDict:params] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        [NetworkProgressHUD hideHud];
        if (responseModel.status == ResponseSuccess) {
            weakSelf.detailModel = [MNDPlusRecordDetailModel mj_objectWithKeyValues:responseModel.data];
            [weakSelf configContents];
        }else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)configContents {
    self.borrowMoneyLabel.text = self.detailModel.sign_amount;
    self.alrealyMoneyLabel.text = self.detailModel.tender_money;
    self.interestLabel.text = self.detailModel.wait_interest_amount;
    self.deadlineLabel.text = [NSString stringWithFormat:@"%@个月",self.detailModel.plan_deadline];
    self.startTimeLabel.text = self.detailModel.sign_start_date;
    self.returnTimeLabel.text = self.detailModel.sign_end_date;
    self.yearAprLabel.text = [NSString stringWithFormat:@"%@%%",self.detailModel.sign_year_apr];
    if (self.detailModel.sign_coupon_apr.floatValue <= 0) {
        self.awardLabel.hidden = YES;
        self.awardTipLabel.hidden = YES;
        self.bottomConstraint.constant = 0;
        
        UIView *headerView = self.tableView.tableHeaderView;
        CGRect newFrame = self.tableView.tableHeaderView.frame;
        newFrame.size.height = newFrame.size.height - 20.5;
        headerView.frame = newFrame;
        [self.tableView beginUpdates];
        self.tableView.tableHeaderView = headerView;
        [self.tableView endUpdates];
       
    }else{
        self.awardLabel.hidden = NO;
        self.awardTipLabel.hidden = NO;
        self.awardLabel.text = [NSString stringWithFormat:@"%@%%",self.detailModel.sign_coupon_apr];
        self.bottomConstraint.constant = 20.5;
    }
        
    //是否可以退出
    if (self.detailModel.sign_can_quit.integerValue == 1) {
        self.exitButton.hidden = NO;
    }else{
        self.exitButton.hidden = YES;
    }
        
    [self.tableView reloadData];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MNDPlusDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:kMNDPlusDetailCell];
    if (indexPath.row == 0) {
        cell.titleLabel.text = @"出借项目";
        cell.subtitleLabel.text = @"展示您的当前出借项目";
        cell.moneyLabel.hidden = YES;
    }else {
        cell.titleLabel.text = @"已赚收益";
        cell.subtitleLabel.text = @"锁定期内可获得利息收入，本金滚动出借";
        cell.moneyLabel.text = [NSString stringWithFormat:@"%@元",self.detailModel.accrued_interest_amount ? self.detailModel.accrued_interest_amount : @"0.00"];
        cell.moneyLabel.hidden = NO;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"MNDTenderProjectViewController" bundle:nil];
        MNDTenderProjectViewController *listVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDTenderProjectViewController"];
        listVC.sign_id = self.detailModel.sign_id;
        [self.navigationController pushViewController:listVC animated:YES];
    }else {
        
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"MNDEarnRecordViewController" bundle:nil];
        MNDEarnRecordViewController *recordVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDEarnRecordViewController"];
        recordVC.sign_id = self.detailModel.sign_id;
        [self.navigationController pushViewController:recordVC animated:YES];
    }
    
}

#pragma mark - Action
//退出项目
- (IBAction)exitProjectAction:(UIButton *)sender {
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:@"您确定要退出该项目吗？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *comfirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [NetworkProgressHUD showHud];
        NSDictionary *params = @{
                                 @"sign_id":self.detailModel.sign_id
                                 };
        [APIManager sendRequestWithURL:API_AUTO_PLUS_EXIT parameters:[MNDSign signedParamWithDict:params] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
            if (responseModel.status == ResponseSuccess) {
                [NetworkProgressHUD showHudMsg:responseModel.msg[@"success"]];
                [self.navigationController popViewControllerAnimated:YES];
            }else {
                [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
            }
            
        } onFailure:^(NSError *error) {
            [NetworkProgressHUD showHudNetworkError:error];
        }];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertVC addAction:comfirmAction];
    [alertVC addAction:cancelAction];
    
    [self presentViewController:alertVC animated:YES completion:nil];
    
}

//查看自助投协议
- (IBAction)checkProtocolAction:(UIButton *)sender {

    kdeclare_weakself;
    [NetworkProgressHUD showHud];
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"sign_id": self.detailModel.sign_id}];
    [APIManager sendRequestWithPath:API_AUTO_PLUS_PROTOCOL parameters:params method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            MNDWebViewController *webVC = [[MNDWebViewController alloc] init];
            webVC.webViewUrl = responseModel.data;
            webVC.naviBarHidden = NO;
            webVC.loadType = LoadTypeLink;
            webVC.title = @"自助投授权委托书";
            UINavigationController *naviVC = [[UINavigationController alloc] initWithRootViewController:webVC];
            [weakSelf presentViewController:naviVC animated:YES completion:^{
             
            }];
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败，请重试"];
            }
        }
        
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
